package com.sfac.springboot.modules.test.service.impl;

import com.sfac.springboot.modules.common.vo.Result;
import com.sfac.springboot.modules.common.vo.Search;
import com.sfac.springboot.modules.test.dao.StudentDao;
import com.sfac.springboot.modules.test.entity.Student;
import com.sfac.springboot.modules.test.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @Description StudentServiceImpl
 * @Author JiangHu
 * @Date 2022/8/19 15:05
 */
@Service
public class StudentServiceImpl implements StudentService {
	@Autowired
	private StudentDao studentDao;

	@Override
	@Transactional
	public Result<Student> insertStudent(Student student) {
		studentDao.saveAndFlush(student);
		return new Result<>(Result.ResultStatus.SUCCESS.code,
				"Insert success.", student);
	}

	@Override
	@Transactional
	public Result<Student> updateStudent(Student student) {
//		studentDao.saveAndFlush(student);
		studentDao.updateStudent(student.getId(),
				student.getStudentName(), student.getUpdateDate());
		return new Result<>(Result.ResultStatus.SUCCESS.code,
				"Update success.", student);
	}

	@Override
	@Transactional
	public Result<Object> deleteStudentById(int id) {
		studentDao.deleteById(id);
		return new Result<>(Result.ResultStatus.SUCCESS.code, "Delete success.");
	}

	@Override
	public Student getStudentById(int id) {
//		return studentDao.getById(id);
		return studentDao.getStudentById(id);
	}

	@Override
	public Page getStudentsBySearch(Search search) {
		// 初始化查询对象
		search.init();

		// 分页和排序功能
		Sort sort = Sort.by(
				search.getDirection().toLowerCase().equals("asc") ?
						Sort.Direction.ASC : Sort.Direction.DESC,
				search.getSort()
		);
		PageRequest pageable = PageRequest.of(
				search.getCurrentPage() - 1,
				search.getPageSize(),
				sort);

		// 查询模板
		Student student = new Student();
		student.setStudentName(search.getKeyword());
		ExampleMatcher matcher = ExampleMatcher
				.matchingAny()
				.withMatcher("studentName", match -> match.contains())
				.withIgnorePaths("id");
		// 根据实体 bean 属性以及设定的模板匹配器规则，到数据库查询
		// 通俗理解：设置查询条件
		Example<Student> example = Example.of(student, matcher);

		return studentDao.findAll(example, pageable);
	}

	@Override
	public List<Student> getStudentsByStudentName(String studentName) {
		return Optional
				.ofNullable(studentDao.findByStudentName(studentName))
				.orElse(Collections.emptyList());
	}
}
